use egui::{Ui, RichText, Color32, Vec2, Stroke, Rounding, Frame};
use crate::app::{App, state::AppEvent};
use crate::ui::theme::AppTheme;
use crate::ui::widgets;
use crate::models::ServerConfig;

pub struct ServersPanel;

impl ServersPanel {
    pub fn render(ui: &mut Ui, app: &App, theme: &AppTheme) -> Option<AppEvent> {
        let mut event = None;
        
        ui.vertical(|ui| {
            ui.add_space(16.0);
            ui.vertical_centered(|ui| {
                ui.heading(RichText::new("服务器管理").size(28.0).color(theme.text));
            });
            ui.add_space(24.0);
            
            // 顶部工具栏
            if let Some(evt) = Self::render_toolbar(ui, app, theme) {
                event = Some(evt);
            }
            
            ui.add_space(16.0);
            ui.separator();
            ui.add_space(16.0);
            
            // 服务器列表
            if let Some(evt) = Self::render_server_list(ui, app, theme) {
                event = Some(evt);
            }
        });
        
        event
    }
    
    fn render_toolbar(ui: &mut Ui, app: &App, theme: &AppTheme) -> Option<AppEvent> {
        let mut event = None;
        
        ui.horizontal(|ui| {
            // 添加服务器按钮
            let add_btn = ui.add(widgets::primary_button(theme, "+ 添加服务器"));
            if add_btn.clicked() {
                event = Some(AppEvent::AddServer);
            }
            
            ui.add_space(16.0);
            
            // 导入按钮
            if ui.add(widgets::secondary_button(theme, "导入")).clicked() {
                // 这里实现导入逻辑
            }
            
            ui.add_space(12.0);
            
            // 导出按钮
            if ui.add(widgets::secondary_button(theme, "导出")).clicked() {
                // 这里实现导出逻辑
            }
            
            // 填充空间，使URL输入框靠右
            ui.add_space(32.0);
            
            // URL输入框 - 静态展示
            ui.label(RichText::new("导入URL:").color(theme.text_secondary));
            ui.label(if !app.import_url.is_empty() { &app.import_url } else { "输入URL..." });
            
            if ui.button("解析").clicked() {
                // 这里实现URL解析逻辑
            }
        });
        
        event
    }
    
    fn render_server_list(ui: &mut Ui, app: &App, theme: &AppTheme) -> Option<AppEvent> {
        let mut event = None;
        
        // 列表滚动区域
        egui::ScrollArea::vertical().show(ui, |ui| {
            // 使用不可变迭代器
            for (idx, server) in app.servers.iter().enumerate() {
                let is_selected = app.current_server_idx == Some(idx);
                
                // 服务器卡片间距
                if idx > 0 {
                    ui.add_space(12.0);
                }
                
                // 服务器卡片背景
                let card_fill = if is_selected {
                    theme.card_background.gamma_multiply(1.2)
                } else {
                    theme.card_background
                };
                
                // 服务器卡片边框
                let card_stroke = if is_selected {
                    Stroke::new(2.0, theme.primary)
                } else {
                    Stroke::new(1.0, theme.panel_background.gamma_multiply(1.5))
                };
                
                // 服务器卡片
                Frame::none()
                    .fill(card_fill)
                    .stroke(card_stroke)
                    .rounding(Rounding::same(12.0))
                    .inner_margin(16.0)
                    .show(ui, |ui| {
                        ui.horizontal(|ui| {
                            // 左侧信息
                            ui.vertical(|ui| {
                                // 服务器名称
                                let name_text = RichText::new(&server.name)
                                    .size(18.0)
                                    .color(if is_selected { theme.primary } else { theme.text })
                                    .strong();
                                ui.label(name_text);
                                
                                ui.add_space(4.0);
                                
                                // 服务器地址和协议
                                ui.horizontal(|ui| {
                                    ui.label(
                                        RichText::new(format!("{}:{}", server.host, server.port))
                                            .color(theme.text_secondary)
                                    );
                                    
                                    ui.label(RichText::new(" | ").color(Color32::from_gray(100)));
                                    
                                    // 显示服务器类型
                                    let server_type_str = match server.server_type {
                                        crate::models::ServerType::Shadowsocks => "Shadowsocks",
                                        crate::models::ServerType::Vmess => "Vmess",
                                        crate::models::ServerType::Trojan => "Trojan",
                                    };
                                    
                                    ui.label(
                                        RichText::new(server_type_str)
                                            .color(theme.text_secondary)
                                    );
                                    
                                    ui.label(RichText::new(" | ").color(Color32::from_gray(100)));
                                    
                                    ui.label(
                                        RichText::new(&server.encryption)
                                            .color(theme.text_secondary)
                                    );
                                });
                            });
                            
                            // 右侧操作按钮
                            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                                let button_height = 28.0;
                                let server_idx = idx; // 在闭包中保存当前索引，防止借用冲突
                                
                                // 删除按钮
                                let delete_btn = ui.button(
                                    RichText::new("×")
                                        .size(18.0)
                                        .color(theme.error)
                                );
                                if delete_btn.clicked() {
                                    event = Some(AppEvent::DeleteServer(server_idx));
                                }
                                
                                ui.add_space(8.0);
                                
                                // 编辑按钮
                                if ui.add_sized(
                                    [70.0, button_height], 
                                    widgets::secondary_button(theme, "编辑")
                                ).clicked() {
                                    event = Some(AppEvent::EditServer(server_idx));
                                }
                                
                                ui.add_space(8.0);
                                
                                // 选择按钮
                                let select_button = ui.add(if is_selected {
                                    widgets::primary_button(theme, "已选择")
                                } else {
                                    widgets::secondary_button(theme, "选择")
                                });
                                
                                if select_button.clicked() {
                                    event = Some(AppEvent::SelectServer(server_idx));
                                }
                            });
                        });
                    });
            }
            
            // 没有服务器的提示
            if app.servers.is_empty() {
                ui.vertical_centered(|ui| {
                    ui.add_space(40.0);
                    ui.label(
                        RichText::new("没有服务器配置")
                            .size(18.0)
                            .color(theme.text_secondary)
                    );
                    ui.add_space(16.0);
                    if ui.button("添加服务器").clicked() {
                        event = Some(AppEvent::AddServer);
                    }
                });
            }
        });
        
        event
    }
} 